// import { catchError, finalize, map, Observable } from "rxjs";
import { TextBuilder } from '../../map/layers/TextLayer';
import { ModelObjType } from '../../shared/types';
import {
  BaseLayer,
  IBaseLayerParams,
  RenderOptions,
} from '../../map/layers/BaseLayer';
import { FilterSpecification, LayerSpecification } from 'mapbox-gl';
import logger from 'loglevel';
import { generateCommonLayout } from '../bizUnit';

export class SharedTextLayer extends BaseLayer {
  sort = 0;
  private options: RenderOptions = {
    layout: {},
    paint: {},
  };
  private filterTypes: Set<ModelObjType> = new Set<ModelObjType>();
  constructor(cfg: IBaseLayerParams) {
    super(cfg);
    this.options = {
      layout: {
        ...generateCommonLayout(),
        'icon-ignore-placement': true,
      },
    };
    this.onload = () => {
      this.showText(['name']);
    };
  }

  filter(conditions: FilterSpecification) {
    const layerLoaded = this.checkLoaded();
    if (!layerLoaded) {
      console.warn(`Layer with ID ${this.layerId} is not loaded yet.`);
      return;
    }
    return this.map.setFilter(this.layerId, conditions);
  }

  addToMap(): string {
    // const textField = this.textBuilder.format();
    const layout = this.options.layout || {};
    const paint = this.options.paint || {};
    const option = {
      id: this.layerId,
      type: 'symbol',
      source: this.sourceId,
      layout,
      paint,
      // filter: []
    } as LayerSpecification;
    // if (this._filter) {
    //   option.filter = this._filter;
    // }
    this.map.addLayer(option);
    return this.layerId;
  }

  showText(properties: string[]) {
    const layerLoaded = this.checkLoaded();
    if (!layerLoaded) {
      console.warn(`Layer with ID ${this.layerId} is not loaded yet.`);
      return;
    }
    const styles: { [key: string]: Record<string, any> } = {
      name: {
        // 'text-color': 'transparent',
        'text-color': '#4c4c4b',
      },
      pid: {
        'text-color': 'green',
      },
    };
    const tb = new TextBuilder();
    properties.forEach((prop, index) => {
      tb.addText()
        .useProperty(prop)
        .setStyle(styles[prop] || {});
      if (index < properties.length - 1) {
        tb.addText().useValue('\n');
      }
    });
    const textField = tb.format();
    logger.info('SharedTextLayer updateLayout textField:', textField);
    this.map.setLayoutProperty(this.layerId, 'text-field', textField);
  }

  // setFilterObjTypes(modelTypes: ModelObjType[]) {
  //   this.filterTypes.clear();
  //   for (const modelType of modelTypes) {
  //     this.filterTypes.add(modelType);
  //   }
  //   this.updateVisible();
  // }

  updateVisibleByObjType(modelType: ModelObjType, visible: boolean) {
    const size = this.filterTypes.size;
    if (visible) {
      this.filterTypes.add(modelType);
    } else {
      this.filterTypes.delete(modelType);
    }
    if (this.filterTypes.size === size) {
      // 没有变化
      return;
    }
    this.updateVisible();
  }

  batchUpdateVisibleByObjTypes(
    data: { modelType: ModelObjType; visible: boolean }[],
  ) {
    if (data.length === 0) {
      return;
    }
    data.forEach((item) => {
      if (item.visible) {
        this.filterTypes.add(item.modelType);
      } else {
        this.filterTypes.delete(item.modelType);
      }
    });
    this.updateVisible();
  }

  private updateVisible() {
    if (this.filterTypes.size === 0) {
      this.hide();
    } else {
      this.show();
    }

    // 创建一个新的过滤条件，结合类型过滤和缩放级别过滤
    const filters = Array.from(this.filterTypes).map((objType) => {
      return [
        'all',
        ['==', ['get', 'type'], objType],
        ['>=', ['zoom'], ['get', 'minN']], // 确保每个类型都包含缩放级别过滤
      ];
    });

    // 组合类型过滤和缩放级别过滤
    // 确保生成的过滤条件格式正确
    const combinedFilter: FilterSpecification = ['any', ...filters];

    // 应用组合过滤条件
    logger.info('应用组合过滤条件:', combinedFilter);
    this.filter(combinedFilter);
  }
}
